<template>
  <div class="excel">
    <!-- 面包屑导航 -->
    <mybreadcrumb />

    <div class="btns">
      <el-button @click="importexcel">导入excel</el-button>
      <el-button @click="exportexcel">导出excel</el-button>
    </div>
    <input ref="inputele" type="file" @change="handleChange">
    <div id="TableContainer"></div>
  </div>
</template>

<script setup>
import {ref} from 'vue'

//导入xlsx库
//导入file-saver库
import * as XLSX from 'xlsx'
import fs from 'file-saver'

var inputele = ref();

//导入逻辑:
//1.选择文件
//2.获取文件
//3.解析文件内容
//4.渲染文件内容到网页

//导出逻辑:
//1.解析dom节点,获取dom节点中的表格数据( 需要用到xlsx库  )
//2.得到数据,生成符合excel格式的数据
//3.生成excel文件( 需要用到file-saver库 )

var importexcel = ()=>{
  inputele.value.click();
}
var exportexcel = ()=>{
  excelExport( document.querySelector('table'),'myexcel' )
}

var handleChange = (e)=>{
  httpRequest( e.target.files[0] )
}

var httpRequest = (file) =>{
  //获取文件,判断文件类型
  const types = file.name.split('.')[1]
  const fileType = ['xlsx', 'xlc', 'xlm', 'xls', 'xlt'].some(
    (item) => item === types
  )
  if (!fileType) {
    alert('格式错误！请重新选择')
    return
  }

  // 方式1（官网推荐、如果有报错就使用方式2）：
  file.arrayBuffer().then(ab => {
    /* Parse file */
    const wb = XLSX.read(ab);
    const ws = wb.Sheets[wb.SheetNames[0]];

    /* Generate HTML */
    document.getElementById('TableContainer').innerHTML = XLSX.utils.sheet_to_html(ws)
  });

}

// 自动分析dom元素导出excel
var excelExport = (table, filename) => {
  // workbook,
  const wb = XLSX.utils.table_to_book(table)

  /* Export to file (start a download) */
  const defaultCellStyle = {
    font: { name: 'Verdana', sz: 13, color: 'FF00FF88' },
    fill: { fgColor: { rgb: 'FFFFAA00' } },
  }
  const wopts = {
    bookType: 'xlsx',
    bookSST: false,
    type: 'binary',
    cellStyle: true,
    defaultCellStyle: defaultCellStyle,
    showGridLines: false,
  }
  const wbout = XLSX.write(wb, wopts)
  const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' })
  fs.saveAs(blob, filename+'.xlsx')
}

var s2ab = (s) => {
  if (typeof ArrayBuffer !== 'undefined') {
    const buf = new ArrayBuffer(s.length);
    const view = new Uint8Array(buf);
    for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
    return buf;
  } else {
    const buf = new Array(s.length);
    for (let i = 0; i !== s.length; ++i) buf[i] = s.charCodeAt(i) & 0xff;
    return buf;
  }
}

</script>

<style scoped lang='scss'>
.excel {
  .btns{
    margin: 20px 0;
  }
  input{
    display: none;
  }
  :deep(table){
    border-collapse: collapse;
    line-height: 40px;
    text-align: center;
    width: 100%;
    tr,td{
      border: 1px solid #ccc;
    }
    tr:nth-child(even){
      background-color: lightblue;
    }
  }

}
</style>